package com.example.cms.Users;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.example.cms.AuthUtils.*;
import com.example.cms.DB.DBUtil;
import com.example.cms.Patients.Patient;
import com.example.cms.Schedules.Schedule;
import com.example.cms.Schedules.SchedulesManager;

public class UsersManager {
    private Scanner scanner;
    private User currentUser;
    private UserService userService;
    private SchedulesManager schedulesManager;
    private Patient patient;


    public UsersManager() {
        this.scanner = new Scanner(System.in);
        this.userService = new UserService();
    }
    // ==================== 用户管理 ====================
    public void showUserMenu() {
        while (true) {
            System.out.println("\n--- 用户管理 ---");
            System.out.println("1. 添加用户");
            System.out.println("2. 查看用户信息");
            System.out.println("3. 修改用户状态");
            System.out.println("4. 重置密码");
            System.out.println("5. 查看用户列表");
            System.out.println("0. 返回主菜单");

            System.out.print("请选择操作: ");
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    addUser();
                    break;
                case "2":
                    viewUser();
                    break;
                case "3":
                    updateUserStatus();
                    break;
                case "4":
                    resetPassword();
                    break;
                case "5":
                    listUsers();
                    break;
                case "0":
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void addUser() {
        System.out.println("\n--- 添加用户 ---");
        try {
            System.out.print("用户名: ");
            String username = scanner.nextLine();

            if (userService.isUsernameExists(username)) {
                System.out.println("用户名已存在！");
                return;
            }

            System.out.print("密码: ");
            String password = scanner.nextLine();

            System.out.print("角色(PATIENT/DOCTOR/ADMIN): ");
            String role = scanner.nextLine().toUpperCase();

            System.out.print("姓名: ");
            String name = scanner.nextLine();

            User user = new User(username, password, role, name);

            if (userService.addUser(user)) {
                System.out.println("用户添加成功！");
            } else {
                System.out.println("用户添加失败！");
            }
        } catch (Exception e) {
            System.out.println("添加失败: " + e.getMessage());
        }
    }

    private void viewUser() {
        System.out.println("\n--- 查看用户信息 ---");
        System.out.print("请输入用户ID: ");
        String input = scanner.nextLine();

        try {
            User user = userService.findUserById(Integer.parseInt(input));

            if (user != null) {
                displayUserInfo(user);
            } else {
                System.out.println("未找到用户信息！");
            }
        } catch (Exception e) {
            System.out.println("查询失败: " + e.getMessage());
        }
    }

    private void updateUserStatus() {
        System.out.println("\n--- 修改用户状态 ---");
        System.out.print("请输入用户ID: ");
        int userId = Integer.parseInt(scanner.nextLine());

        try {
            User user = userService.findUserById(userId);
            if (user == null) {
                System.out.println("用户不存在！");
                return;
            }

            displayUserInfo(user);
            System.out.print("新状态(ACTIVE/INACTIVE): ");
            String newStatus = scanner.nextLine().toUpperCase();

            if (userService.updateUserStatus(userId, newStatus)) {
                System.out.println("用户状态更新成功！");
            } else {
                System.out.println("用户状态更新失败！");
            }
        } catch (Exception e) {
            System.out.println("修改失败: " + e.getMessage());
        }
    }

    private void resetPassword() {
        System.out.println("\n--- 重置密码 ---");
        System.out.print("请输入用户ID: ");
        int userId = Integer.parseInt(scanner.nextLine());

        try {
            User user = userService.findUserById(userId);
            if (user == null) {
                System.out.println("用户不存在！");
                return;
            }

            System.out.print("新密码: ");
            String newPassword = scanner.nextLine();

            if (userService.changePassword(userId, newPassword)) {
                System.out.println("密码重置成功！");
            } else {
                System.out.println("密码重置失败！");
            }
        } catch (Exception e) {
            System.out.println("重置失败: " + e.getMessage());
        }
    }

    private void listUsers() {
        System.out.println("\n--- 用户列表 ---");
        try {
            List<User> users = getAllUsers();
            if (users.isEmpty()) {
                System.out.println("暂无用户数据");
                return;
            }

            System.out.println("ID\t用户名\t角色\t姓名\t状态");
            System.out.println("----------------------------------------");
            for (User user : users) {
                System.out.printf("%d\t%s\t%s\t%s\t%s\n",
                        user.getId(),
                        user.getUsername(),
                        AuthUtil.getRoleDisplayName(user.getRole()),
                        user.getName(),
                        user.getStatus());
            }
        } catch (Exception e) {
            System.out.println("获取用户列表失败: " + e.getMessage());
        }
    }


    private void displayUserInfo(User user) {
        System.out.println("\n=== 用户信息 ===");
        System.out.println("用户ID: " + user.getId());
        System.out.println("用户名: " + user.getUsername());
        System.out.println("角色: " + AuthUtil.getRoleDisplayName(user.getRole()));
        System.out.println("姓名: " + user.getName());
        System.out.println("状态: " + user.getStatus());
    }

    public String getDoctorNameBySchedule(int scheduleId) {
        Schedule schedule = schedulesManager.findScheduleById(scheduleId);
        return schedule != null ? schedule.getDoctorName() : "未知";
    }

    public void changePassword() {
        if (currentUser == null) {
            System.out.println("用户未登录！");
            return;
        }

        System.out.println("\n--- 修改密码 ---");
        System.out.print("请输入新密码: ");
        String newPassword = scanner.nextLine();

        if (userService.changePassword(currentUser.getId(), newPassword)) {
            System.out.println("密码修改成功！");
        } else {
            System.out.println("密码修改失败！");
        }
    }


    // 用户相关操作方法
    private List<User> getAllUsers() {
        List<User> users = new ArrayList<>();
        String sql = "SELECT * FROM users ORDER BY created_time DESC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                users.add(mapResultSetToUser(rs));
            }
        } catch (SQLException e) {
            System.err.println("获取所有用户失败: " + e.getMessage());
        }
        return users;
    }


    private User mapResultSetToUser(ResultSet rs) throws SQLException {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setRole(rs.getString("role"));
        user.setName(rs.getString("name"));
        user.setStatus(rs.getString("status"));
        patient.setCreateTime(rs.getTimestamp("created_time").toLocalDateTime());
        return user;


    }
    public void setSchedulesManager(SchedulesManager schedulesManager) {
        this.schedulesManager = schedulesManager;
    }

    public void setCurrentUser(User currentUser) {
        this.currentUser = currentUser;
    }
}
